package com.bjsxt.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.vo.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class WevSocketMessageHandler implements IWsMsgHandler {
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        String clientIp =  httpRequest.getClientIp();
        log.info("开始和{}客户端建立连接",clientIp);

        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        String clientIp =  httpRequest.getClientIp();
        log.info("{}客户端建立连接成功",clientIp);



    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {

        Tio.remove(channelContext,"remove channelContext" );

        return null;
    }

    /**
     * 文本处理
     * @param wsRequest
     * @param
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {

        log.info("前端发送数据过来");

        if (Objects.equals("ping", text)) {
            return "pong";
        }

        JSONObject payload = JSONObject.parseObject(text);
        String sub = payload.getString("sub");
        String req = payload.getString("req");
        String cancel = payload.getString("cancel");
        String id = payload.getString("id");
        String authorization = payload.getString("authorization");
            if (StringUtils.hasText(sub)){
                Tio.bindGroup(channelContext,sub);
            }

        if (StringUtils.hasText(cancel)){
            Tio.unbindGroup(cancel,channelContext);
        }

        if (StringUtils.hasText(authorization) && authorization.startsWith("bearer ")){
           String token = authorization.replaceAll("bearer ","");

            Jwt jwt = JwtHelper.decode(token);
            String claims = jwt.getClaims();
            JSONObject jwtJson = JSON.parseObject(claims);
            String userId = jwtJson.getString("user_name") ;

            JSONArray authorities1 = jwtJson.getJSONArray("authorities");

            Tio.unbindUser(channelContext.getTioConfig(),userId);
        }
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setCanceled(cancel);
        responseEntity.setId(id);
        responseEntity.setSubbed(sub);
        responseEntity.setStatus("ok");
        responseEntity.setCh(sub);
        responseEntity.setEvent(req);

        return  new ResponseEntity().build();



//        //1.在前端推送模式里，使用最多的是订阅模式
//
//        Tio.bindGroup(channelContext,"test");
//
//        //2.前端有token时，得到具体用户
//
//
//        //return  给别人发送的信息
//        return WsResponse.fromText("你好","utf-8");
    }
}
